package com.leyou.page.service.impl;

import com.leyou.item.entity.*;
import com.leyou.page.client.BrandClient;
import com.leyou.page.client.CategoryClient;
import com.leyou.page.client.GoodsClient;
import com.leyou.page.client.SpecClient;
import com.leyou.page.service.PageService;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.thymeleaf.TemplateEngine;
import org.thymeleaf.context.Context;

import java.io.*;
import java.util.*;

/**
 * @author linzx
 * @date 2020/3/28
 */
@Service
public class PageServiceImpl implements PageService {

    @Autowired
    private GoodsClient goodsClient;
    @Autowired
    private BrandClient brandClient;
    @Autowired
    private CategoryClient categoryClient;
    @Autowired
    private SpecClient specClient;
    @Autowired
    private TemplateEngine templateEngine;

    @Override
    public Map<String, Object> loadData(Long spuId) {
        Map<String,Object> map = new HashMap<>();
        Spu spu = goodsClient.querySpuById(spuId);
        List<Sku> skus = goodsClient.findSkuBySpuId(spuId);
        SpuDetail spuDetail = goodsClient.findSpuDetailById(spuId);
        List<Category> categories = categoryClient.queryCategoryByIds(Arrays.asList(spu.getCid1(), spu.getCid2(), spu.getCid3()));
           Brand brand = brandClient.findBrandById(spu.getBrandId());
        List<SpecGroup> groups = specClient.findSpecGroupByCid(spu.getCid3());
        List<SpecParam> params = specClient.findSpecByParams(spu.getCid3(),null,null);
       Map<Long,String> paramMap = new HashMap<>();
        params.forEach(specParam -> paramMap.put(specParam.getId(),specParam.getName()));


        // 封装spu
        map.put("spu", spu);
        // 封装spuDetail
        map.put("spuDetail", spuDetail);
        // 封装sku集合
        map.put("skus", skus);
        // 分类
        map.put("categories", categories);
        // 品牌
        map.put("brand", brand);
        // 规格参数组
        map.put("groups", groups);
        // 查询特殊规格参数
        map.put("paramMap", paramMap);
        return map;
    }

    @Override
    public void deleteHtml(Long spuId) {
        String classPath = PageServiceImpl.class.getClassLoader().getResource("").getPath();
        File file = new File(classPath + spuId + ".html");
        file.deleteOnExit();
    }

    private File createDirs(String dirPath,String fileName) {
        if (StringUtils.isBlank(dirPath) || "/".equals(dirPath.trim()) || "\\".equals(dirPath.trim())) {
            throw new RuntimeException("文件路径必须存在") ;
        }
        String classPath = PageServiceImpl.class.getClassLoader().getResource("").getPath();
        if (System.getProperty("os.name").toLowerCase().startsWith("win")) {
            classPath = classPath.substring(1);
        }
        classPath += dirPath ;
        File file = new File(classPath);
        if (!file.exists()) {
            if (!file.mkdirs()) {
                throw new RuntimeException("添加文件失败");
            }
        }
        return new File(classPath + fileName);
    }

    @Override
    public void createHtml(Long spuId) {
       File file = createDirs("item",spuId +".html");
            file.deleteOnExit();
        Context context = new Context();
        Writer writer = null;
        try {
            writer = new PrintWriter(file,"UTF-8");
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        context.setVariables(loadData(spuId));
        templateEngine.process("item",context,writer);

    }
}
